import { Injectable  } from '../../support'
import { getMessagePromptTxt } from './util'
import { completions } from '@backend/app/chat/chatGPT/sender'
import { isArray, escape, escapeRegExp } from 'lodash'
import { get_chat } from '@backend/includes/chat'
import model from '@backend/model'
import { chatGPTParseText, isStopParse } from '@/both/utils'


process.on("uncaughtException", function (err) {
  console.error(`Caught exception: ${err}`);
});

// MyService.ts
@Injectable()
export class ChatService {
  constructor() { /* do nothing */ console.log('init chatservice')  }

  async chatSendMessage( p : any , e: any ){
    const message = p.message || '你好'
    const callbackEventName = p.callbackEvent
    const view = e.sender
    const chatId = p.chat_id
    let messageId = 0

    let body: Object = {}
    if ( isArray( message) ) {
      body = {
        model: 'gpt-3.5-turbo-16k-0613',
        messages: message,
        stream: true
      }
    } else {
      body = {
          prompt: message,
          max_tokens: 2048, 
          model: "text-davinci-003",
          // Set stream to true to receive each token as it is generated.
          stream: true
      }
    }
    model("Message").then(async ({ Message })=>{
      const msg = Message.create({
          chat_id: chatId,
          prompt: getMessagePromptTxt(message)
      });
      const rec = await Message.save(msg)
      messageId = rec.id
      console.log('rec....', rec)
    })
    
    const opts = body;

    let repeatStr = "";
    await completions( opts , ( parsed: any)=>{
      const str = chatGPTParseText(parsed)
      repeatStr += escape(str);
      callbackEventName && view && view.send(callbackEventName, parsed )
      if( isStopParse(parsed) ){
        model("Message").then(async ({ Message })=>{
          const msg = await Message.findOne({
            where: {
              id: messageId
            }
          })
          msg.repeat = escape(repeatStr)
          Message.save(msg)
        })
      }
    });

    return true;  
  }

  async chatCompletions( p: any, e: any ){

  }

  async chatMessageList(id: number | string, param: object = {}): Promise< Record<string, any>[] >{
    if(!id) return []
    const chat = await get_chat( id )
    const list = await chat.getMessageList()
    return list
  }
}